package com.geohey.utils;

import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

public class JsonUtils {

	private static ObjectMapper mapper;

	private JsonUtils() {
	}

	static {
		mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Inclusion.NON_NULL);
	}

	public static String toJson(Object obj) {
		if (obj == null)
			return null;
		try {
			return mapper.writeValueAsString(obj);
		} catch (Exception ex) {
		}
		return null;
	}

	public static <T> T readObject(String json, Class<T> objClass) {
		if (json == null)
			return null;
		try {
			return mapper.readValue(json, objClass);
		} catch (Exception ex) {
		}
		return null;
	}

	public static <T> List<T> readArray(String json, Class<T> objClass) {
		if (json == null)
			return null;
		try {
			return mapper.readValue(json, mapper.getTypeFactory()
					.constructCollectionType(List.class, objClass));
		} catch (Exception ex) {
		}
		return null;
	}

	public static Map readMap(String json) {
		if (json == null)
			return null;
		try {
			return mapper.readValue(json, Map.class);
		} catch (Exception ex) {
		}
		return null;
	}
}
